package handler

import (
	"context"
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"log"
	"net/http"
	"zg6/zg6_month/client/global"
	"zg6/zg6_month/ordersrv/ordersrv"

	"github.com/zeromicro/go-zero/rest/httpx"
	"zg6/zg6_month/client/internal/logic"
	"zg6/zg6_month/client/internal/svc"
	"zg6/zg6_month/client/internal/types"
)

func CallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()

		if err := global.Client.VerifySign(r.Form); err != nil {
			log.Println("回调验证签名发生错误", err)
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte("回调验证签名发生错误"))
			return
		}

		log.Println("回调验证签名通过")

		// 示例一：使用已有接口进行查询
		var outTradeNo = r.Form.Get("out_trade_no")
		var p = alipay.TradeQuery{}
		p.OutTradeNo = outTradeNo

		rsp, err := global.Client.TradeQuery(p)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte(fmt.Sprintf("验证订单 %s 信息发生错误: %s", outTradeNo, err.Error())))
			return
		}

		if rsp.IsFailure() {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte(fmt.Sprintf("验证订单 %s 信息发生错误: %s-%s", outTradeNo, rsp.Msg, rsp.SubMsg)))
			return
		}
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(fmt.Sprintf("订单 %s 支付成功", outTradeNo)))
		fmt.Println("回调成功")

		var req types.Syn
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		_, err = svcCtx.OrderSrv.SaveOrder(context.Background(), &ordersrv.CreateOrderRes{OrderSn: rsp.OutTradeNo})
		if err != nil {
			panic(err)
		}
		l := logic.NewCallbackLogic(r.Context(), svcCtx)
		resp, err := l.Callback(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
